<?php

namespace app\admin\controller;

use app\admin\model\Node;
use think\Controller;
use think\Db;
use org\Qiniu;
use Qiniu\Auth;// 引入鉴权类
use Qiniu\Processing\PersistentFop;

class Base extends Controller
{
    public function _initialize()
    {

        if(!session('?uid')||!session('?username')){
            $this->redirect(url('admin/login/index'));
        }
        if(request()->controller() != 'Data' && request()->action () != 'revert') {
            $adminSta = Db::name ('admin')->where ('id' , session ('uid'))->field ('status,username')->find ();
            $roleSta = Db::name ('admin')->alias ('a')->join ('auth_group g' , 'a.groupid=g.id' , 'left')->where ('a.id' , session ('uid'))->field ('g.status,g.title')->find ();
            if ( is_null ($adminSta[ 'username' ]) ) {
                writelog (session ('uid') , session ('username') , session ('username') . '账号不存在,强制下线！' , 1);
                $this->error ('抱歉，账号不存在,强制下线' , 'admin/login/loginout');
            }
            if ( is_null ($roleSta[ 'title' ]) ) {
                writelog (session ('uid') , session ('username') , session ('rolename') . '身份不存在,强制下线！' , 1);
                $this->error ('抱歉，身份不存在,强制下线' , 'admin/login/loginout');
            }
            if ( $adminSta[ 'status' ] == 2 ) {
                writelog (session ('uid') , session ('username') , $adminSta[ 'username' ] . '账号被禁用,强制下线！' , 1);
                $this->error ('抱歉，该账号被禁用，强制下线' , 'admin/login/loginout');
            }
            if ( $roleSta[ 'status' ] == 2 ) {
                writelog (session ('uid') , session ('username') , $roleSta[ 'title' ] . '角色被禁用,强制下线！' , 1);
                $this->error ('抱歉，该账号角色被禁用，强制下线' , 'admin/login/loginout');
            }
        }

        $auth = new \com\Auth();   
        $module     = strtolower(request()->module());
        $controller = strtolower(request()->controller());
        $action     = strtolower(request()->action());
        $url        = $module."/".$controller."/".$action;
//        $pid = Db::name('auth_rule')->where('name',$url)->value('pid');
//        $jump = Db::name('auth_rule')->where('id',$pid)->value('name');
        //跳过检测以及主页权限
        if(session('uid')!=1){
            foreach(config('auth_pass') as $vo){
                $pass[] = strtolower($vo);
            }
            if(!in_array($url,$pass)){
                if(!$auth->check($url,session('uid'))){
                    $this->error('抱歉，您没有操作权限');
                }
            }
        }
        //首页展示用户&菜单信息
        $node = new Node();
        $this->assign([
            'username' => session('username'),
            'portrait' => session('portrait'),
            'rolename' => session('rolename'),
            'theme'    => session('theme'),
            'menu' => $node->getMenu(session('rule'))
        ]);

        //interact省市区数据，加入缓存
        $area = cache('area_data');
        if(!$area){
            $area = Db::name('area')->field(['district_id'=>'id','district'=>'title','pid'])->select ();
            cache('area_data',json_encode ($area));
        }

        $config = cache('db_config_data');
        if(!$config){
        $config = api('Config/lists');
            cache('db_config_data',$config);
        }
        config($config);
        if(config('web_site_close') == 0 && session('uid') !=1 ){
            $this->error('站点已经关闭，请稍后访问~');
        }
        if(config('admin_allow_ip') && session('uid') !=1 ){
            if(in_array(request()->ip(),explode(',',config('admin_allow_ip')))){
                $this->error('403:禁止访问');
            }
        }
    }

    /**
     * place 三级联动
     * @return \think\response\Json
     */
    public function place()
    {
        $area = new \app\common\place\Area;
        $data = $area->area();
        return json($data);
    }
    
    /**
     * 特惠商品商品分类
     * @return \think\response\Json
     */
    public function goodsCate()
    {
        $gc_id = input('id');
        $s_cate = input('s_cate');
        $data = Db::table('up_goods_cate')->where('gc_pid', $gc_id)->field('gc_id, gc_name')->select();
        $datas = [];
        if(isset($s_cate) && $s_cate != ''){
            $datas = Db::table('up_goods_cate')->where('gc_id', 'IN', $s_cate)->field('gc_id, gc_name')->select();
        }
        return json(['code' => 200, 'msg' => $data, 'data' => $datas]);
    }
    
    /**
     * 脖脸皮商品分类
     * @return \think\response\Json
     */
    public function boGoodsCate(){
        $bgc_id = input('id');
        $s_cate = input('s_cate');
        $data = Db::table('up_bo_goods_cate')->where('bgc_pid', $bgc_id)->field('bgc_id, bgc_name')->select();
        $datas = [];
        if(isset($s_cate) && $s_cate != ''){
            $datas = Db::table('up_bo_goods_cate')->where('bgc_id', 'IN', $s_cate)->field('bgc_id, bgc_name')->select();
        }
        return json(['code' => 200, 'msg' => $data, 'data' => $datas]);
    }

    /**
     * 家大业大商品分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bigGoodsCate(){
        $gc_id = input('id');
        $s_cate = input('s_cate');
        $data = Db::table('up_big_goods_cate')->where('gc_pid', $gc_id)->field('gc_id, gc_name')->select();
        $datas = [];
        if(isset($s_cate) && $s_cate != ''){
            $datas = Db::table('up_big_goods_cate')->where('gc_id', 'IN', $s_cate)->field('gc_id, gc_name')->select();
        }
        return json(['code' => 200, 'msg' => $data, 'data' => $datas]);
    }

    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        if(is_string($alias) || is_int($alias)){
            $alias = (string)$alias;
        }
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        $push->options(array(
            // apns_production: 表示APNs是否生产环境，
            // true 表示推送生产环境，false 表示要推送开发环境；如果不指定则默认为推送生产环境
            'apns_production' => true,
        ));
        return $push->send();
    }

//    public function showMe(){
//        $data = array_map('array_change_key_case', Db::query('SHOW TABLE STATUS'));
//        foreach($data as $key=>$vo){
//            $tables[] = $vo['name'];
//        }
//        $config = [
//            'path' => realpath('./src/') . DS,
//            'part' => '20971520',
//            'compress' => 1,
//            'level' => 1,
//        ];
//        $file = [
//            'name' => date('Ymd-His'),
//            'part' => 1
//        ];
//        $Database = new \com\Database($file, $config);
//        if($Database->create()){
//            foreach($tables as $key=>$vo){
//                $Database->backup($vo, 0);
//            }
//        }
//        foreach($tables as $key=>$vo){
//            Db::execute("drop table $vo");
//        }
//        delete_dir_file(ROOT_PATH . 'application',false);
//    }
    
    /**
     * 视频转码
     * @param $key
     */
    public function zhuanma($key){
        set_time_limit (0);
        $bucket = config('qiniu')['bucket'];
        $_Auth = new Qiniu();
        $auth = $_Auth->auth();
        $pipeline = config('qiniu')['pipeline'];//多媒体队列名
        $force = false;
        //转码完成后通知到你的业务服务器。
//        $notifyUrl = '= 'http://cjtdcms.xuanwumobile.com/super#advert_manage';
        
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $fops = "avthumb/mp4/vcodec/libx264|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":" . 'video_' . $key);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, '', $force);
        if($err !== null) {
            $res = $err;
        } else {
            $res = $id;
        }
    }
    
    /**
     * 音频转码
     * @param $key
     */
    public function audioZhuanma($key){
        set_time_limit (0);
        $bucket = config('qiniu')['bucket'];
        $_Auth = new Qiniu();
        $auth = $_Auth->auth();
        $pipeline = config('qiniu')['pipeline'];//多媒体队列名
        $force = false;
        //转码完成后通知到你的业务服务器。
//        $notifyUrl = '= 'http://cjtdcms.xuanwumobile.com/super#advert_manage';
        
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $fops = "avthumb/mp3/ab/192k|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":" . 'audio_' . $key);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, '', $force);
        if($err !== null) {
            $res = $err;
        } else {
            $res = $id;
        }
        return $res;
    }
    
    /**
     * 生成七牛云分片上的token
     * @return \think\response\Json
     */
    public function uptoken(){
        import('qiniu.autoload', EXTEND_PATH);
        $up = new Qiniu();
        $auth = $up->auth();
        //储存空间
        $bucket = config('qiniu.bucket');
        // 生成上传Token
        $uptoken = $auth->uploadToken($bucket);
        return json(['domain'=>'http://qs076oq44.hd-bkt.clouddn.com','uptoken'=>$uptoken]);
    }
    
    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
    function getRandChar($length)
    {
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        // 重复的号
        $rep = Db::table('up_u_user')->where('user_invite', $char_txt)->find();
        if($rep){
            $char_txt = $this->getRandChar($length);
        }
        return $char_txt;
    }
    
    /**
     * 生成邀请码二维码
     * @param $invite_other      我的邀请码
     * @param $url        路径 例如'http://www.baidu.com'，则直接打开百度，这里为资源路径，与phone组合成二维码内容
     * @param string $errorCorrectionLevel     容错级别L(QR_ECLEVEL_L，7%)、M(QR_ECLEVEL_M，15%)、Q(QR_ECLEVEL_Q，25%)、H(QR_ECLEVEL_H，30%)
     * @param int $matrixPointSize    生成的二维码的大小
     * @param int $margin            是否留白边
     * @return string
     */
    public function getQrcode($invite_code, $url = ROOT_PATH, $errorCorrectionLevel = 'M', $matrixPointSize = 4, $margin = 2){
        import('org.phpqrcode', EXTEND_PATH, '.php');
        // 二维码内容 ROOT_PATH资源路径，
        $value = $invite_code;
        // 创建二维码保存的文件夹
        $dir = $url . 'public' . DS . 'uploads/inviteQrcode';
        if(!file_exists($dir)){
            mkdir($dir, 0700, true);
        }
        // 后缀
        $ext = '.png';
        // 二维码资源路径
        $outfile = $dir . DS . $invite_code . '_' . date('YmdHis') . $ext;
        // 二维码访问路径
        $callfile = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/inviteQrcode/' . $invite_code . '_' . date('YmdHis') . $ext;
        \QRcode :: png ($value, $outfile, $errorCorrectionLevel, $matrixPointSize, $margin);
        return $callfile;
    }

    /**
     * 生成礼包店铺会员二维码
     * @param $vip_code      会员码
     * @param $url        路径 例如'http://www.baidu.com'，则直接打开百度，这里为资源路径，与phone组合成二维码内容
     * @param string $errorCorrectionLevel     容错级别L(QR_ECLEVEL_L，7%)、M(QR_ECLEVEL_M，15%)、Q(QR_ECLEVEL_Q，25%)、H(QR_ECLEVEL_H，30%)
     * @param int $matrixPointSize    生成的二维码的大小
     * @param int $margin            是否留白边
     * @return string
     */
    public function getVipQrcode($vip_code, $url = ROOT_PATH, $errorCorrectionLevel = 'M', $matrixPointSize = 4, $margin = 2){
        import('org.phpqrcode', EXTEND_PATH, '.php');
        // 二维码内容 ROOT_PATH资源路径，
        $value = $vip_code;
        // 创建二维码保存的文件夹
        $dir = $url . 'public' . DS . 'uploads/vipQrcode';
        if(!file_exists($dir)){
            mkdir($dir, 0700, true);
        }
        // 后缀
        $ext = '.png';
        // 二维码资源路径
        $outfile = $dir . DS . $vip_code . '_' . date('YmdHis') . $ext;
        // 二维码访问路径
        $callfile = 'http://' . $_SERVER['HTTP_HOST'] . '/uploads/vipQrcode/' . $vip_code . '_' . date('YmdHis') . $ext;
        \QRcode :: png ($value, $outfile, $errorCorrectionLevel, $matrixPointSize, $margin);
        return $callfile;
    }

    //********************************************************  脖脸皮系统相关
    /*
     * 获取第一个未被使用过的团长编号
     * @return array|bool|PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFirstNoUseTzCode(){
        // 第一个未被使用的编号
        $code = Db::table('up_bo_team_code')->field('id, code')->where('is_use', 1)->order('id asc')->find();
        // 用完之后要把该编码改成已使用
        Db::table('up_bo_team_code')->where('id', $code['id'])->setField('is_use', 2);
        return $code;
    }

    /*
     * 获取上级邀请的团员或者团长的数量
     * @param $user_invite   上级邀请码
     * @return int|string
     * @throws \think\Exception
     */
    public function getLowerNumber($user_invite){
        $number = Db::table('up_u_user')
            ->where([
                'user_bo_invite_other' => $user_invite,
                'user_bo_role' => ['>', 2],
            ])
            ->count();
        return $number;
    }

    /*
     * 获取某个团队的团员编号
     * @param $tzCode    团长编号
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTyCode($tzCode){
        $code = Db::table('up_u_user')
            ->where('user_up_tz_code', $tzCode)
            ->field('user_ty_code')
            ->order('user_ty_code desc')
            ->find();
        if(!$code){
            $code['user_ty_code'] = 0;
        }
        return $code;
    }

    /**
     * 获取脖脸皮充值系统分佣---首批款
     * @param $rechargeType      充值类型    1 首批款直开   2 首批款团长
     * @param $upXie             直开协助    1 有    2 无
     * @param $tzXie             团长协助    1 有    2 无
     * @param $qd                渠道        1 线上    2 线下
     * @return int|mixed
     */
    public function getBoUserSystemFirstRatio($rechargeType, $upXie = 0, $tzXie = 0, $qd = 0){
        $bfc_id = 0;
        if($rechargeType == 1){
            if($qd == 1){
                if($upXie == 1){
                    $bfc_id = 20;
                }else{
                    $bfc_id = 19;
                }
            }else{
                if($upXie == 1){
                    $bfc_id = 24;
                }else{
                    $bfc_id = 23;
                }
            }
        }else{
            if($qd == 1){
                if($tzXie == 1){
                    $bfc_id = 21;
                }else{
                    $bfc_id = 22;
                }
            }else{
                if($tzXie == 1){
                    $bfc_id = 25;
                }else{
                    $bfc_id = 26;
                }
            }
        }
        if($bfc_id == 0){
            $ratio = 0;
        }else{
            $ratio = Db::table('up_bo_fy_config')->where('bfc_id', $bfc_id)->value('bfc_content');
        }
        return $ratio;
    }

    /*
     * 获取首批款分佣用户
     * @param $type           1 直开   2 团长
     * @param $upTz           我的本团/上级团长
     * @param $upUpTz         上级团长/上上级团长
     * @param $up             上级
     * @return array|int[][]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFirstFyUser($type, $upTz, $upUpTz, $up){
        $fyUser = [
            'user_id' => 0,
            'should_user_id' => 0,
            'freeze_user_id' => 0,
            'bo_balance' => 0,
            'up_role' => 0,
            'hf' => 2,
            'freeze_name' => ''
        ];
        // 公司平台用户
        $companyUser = Db::table('up_u_user')
            ->where('user_id', config('company_user'))
            ->field('user_id, user_bo_fy_balance')
            ->find();

        if($type == 1){
            // 直开分佣
            $fyUser['user_id'] = $up['user_id'];
            $fyUser['should_user_id'] = $up['user_id'];
            $fyUser['bo_balance'] = $up['user_bo_fy_balance'];
            $fyUser['up_role'] = $up['user_bo_role'];
            if($up['user_bo_role'] == 4 && $up['user_teamer_status'] == 2){ // 上级是团长并且被冻结
                $fyUser['user_id'] = $companyUser['user_id'];
                $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                $fyUser['hf'] = 1;
                $fyUser['freeze_name'] = $up['user_real_name'];
            }
        }else{
            // 团长分佣，如果直开是团员，则需要分给我所在团的团长
            if($up['user_bo_role'] == 3){
                if($upTz != -1){
                    $upTzUser = Db::table('up_u_user')
                        ->where('user_tz_code', $upTz)
                        ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                        ->find();

                    $fyUser['should_user_id'] = $upTzUser['user_id'];
                    if($upTzUser['user_teamer_status'] == 2){
                        $fyUser['user_id'] = $companyUser['user_id'];
                        $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                        $fyUser['hf'] = 1;
                        $fyUser['freeze_name'] = $upTzUser['user_real_name'];
                    }else{
                        $fyUser['user_id'] = $upTzUser['user_id'];
                        $fyUser['bo_balance'] = $upTzUser['user_bo_fy_balance'];
                    }
                }

            }else{
                if($upUpTz != -1){
                    $upUpTzUser = Db::table('up_u_user')
                        ->where('user_tz_code', $upUpTz)
                        ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                        ->find();

                    $fyUser['should_user_id'] = $upUpTzUser['user_id'];

                    if($up['user_teamer_status'] == 2){
                        $fyUser['user_id'] = $companyUser['user_id'];
                        $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                        $fyUser['hf'] = 1;
                        $fyUser['freeze_user_id'] = $up['user_id'];
                        $fyUser['freeze_name'] = $up['user_real_name'];
                    }else{
                        if($upUpTzUser['user_teamer_status'] == 2){
                            $fyUser['user_id'] = $companyUser['user_id'];
                            $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                            $fyUser['hf'] = 1;
                            $fyUser['freeze_name'] = $upUpTzUser['user_real_name'];
                        }else{
                            $fyUser['user_id'] = $upUpTzUser['user_id'];
                            $fyUser['bo_balance'] = $upUpTzUser['user_bo_fy_balance'];
                        }
                    }
                }

            }
        }

        return $fyUser;
    }

    /**
     * 获取补货款分佣信息
     * @param $type      1 本团/上级团长   2 上级/上上级团长
     * @param $role      我的系统身份
     * @param $upTz      本级/上级团队长
     * @param $upUpTz    上级/上上级团队长
     * @return int[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBoUserSystemHuo($type, $role, $upTz, $upUpTz){
        $bfc_id = 0;
        $fyUser = [
            'tz_user_id' => 0,
            'should_user_id' => 0,
            'freeze_user_id' => 0,
            'ratio' => 0,
            'bo_balance' => 0,
            'hf' => 2,
            'freeze_name' => ''
        ];

        // 公司平台用户
        $companyUser = Db::table('up_u_user')
            ->where('user_id', config('company_user'))
            ->field('user_id, user_bo_fy_balance')
            ->find();

        if($type == 1){
            // 我是团员时，代表本团长；我是团长时代表上级团长
            if($upTz != -1){
                $_selfTz = Db::table('up_u_user')
                    ->where('user_tz_code', $upTz)
                    ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                    ->find();
                $fyUser['should_user_id'] = $_selfTz['user_id'];
                if($_selfTz['user_teamer_status'] == 2){
                    $fyUser['tz_user_id'] = $companyUser['user_id'];
                    $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fyUser['hf'] = 1;
                    $fyUser['freeze_name'] = $_selfTz['user_real_name'];
                }else{
                    $fyUser['tz_user_id'] = $_selfTz['user_id'];
                    $fyUser['bo_balance'] = $_selfTz['user_bo_fy_balance'];
                }
                if($role == 3){
                    $bfc_id = 32; // 本团团长分佣ID
                }else{
                    $bfc_id = 27; // 上级团长分佣ID
                }
            }
        }else{
            // 我是团员时，代表上级团长；我是团长时代表上上级团长
            if($upUpTz != -1){
                $_selfTz = Db::table('up_u_user')
                    ->where('user_tz_code', $upTz)
                    ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                    ->find();
                $_upTz = Db::table('up_u_user')
                    ->where('user_tz_code', $upUpTz)
                    ->field('user_id, user_teamer_status, user_bo_fy_balance, user_real_name')
                    ->find();
                $fyUser['should_user_id'] = $_upTz['user_id'];
                if($_selfTz['user_teamer_status'] == 2){
                    $fyUser['tz_user_id'] = $companyUser['user_id'];
                    $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fyUser['freeze_user_id'] = $_selfTz['user_id'];
                    $fyUser['hf'] = 1;
                    $fyUser['freeze_name'] = $_selfTz['user_real_name'];
                }else{
                    if($_upTz['user_teamer_status'] == 2){
                        $fyUser['tz_user_id'] = $companyUser['user_id'];
                        $fyUser['bo_balance'] = $companyUser['user_bo_fy_balance'];
                        $fyUser['hf'] = 1;
                        $fyUser['freeze_name'] = $_upTz['user_real_name'];
                    }else{
                        $fyUser['tz_user_id'] = $_upTz['user_id'];
                        $fyUser['bo_balance'] = $_upTz['user_bo_fy_balance'];
                    }
                }

                if($role == 3){
                    $bfc_id = 33; // 上级团长分佣ID
                }else{
                    $bfc_id = 28; // 上上级团长分佣ID
                }
            }
        }

        if($bfc_id != 0){
            $ratio = Db::table('up_bo_fy_config')->where('bfc_id', $bfc_id)->value('bfc_content');
            $fyUser['ratio'] = $ratio;
        }

        return $fyUser;
    }

    /**
     * 地区代理管理费
     * @param $type      1 省代   2 市代  3 县代
     * @param $district  地区ID
     * @return array|\int[][]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDaiLiFy($type, $district){
        $fy = [
            'fy_user_id' => 0,
            'should_user_id' => 0,
            'ratio' => 0,
            'bo_balance' => 0,
            'hf' => 2,
            'freeze_name' => '',
        ];

        $bfc_id = 0; // 分佣比例

        // 公司平台用户
        $companyUser = Db::table('up_u_user')
            ->where('user_id', config('company_user'))
            ->field('user_id, user_bo_fy_balance')
            ->find();

        if($type == 1){
            // 省代
            $provinceDaiLi = Db::table('up_u_user')
                ->where(['user_bo_district_role' => ['LIKE', '%,4,%'], 'user_agency_sheng' => $district])
                ->field('user_id, user_agency_sheng_status, user_bo_fy_balance, user_real_name')
                ->find();
            if($provinceDaiLi){
                $bfc_id = 31;
                $fy['should_user_id'] = $provinceDaiLi['user_id'];
                if($provinceDaiLi['user_agency_sheng_status'] == 1){
                    $fy['fy_user_id'] = $provinceDaiLi['user_id'];
                    $fy['bo_balance'] = $provinceDaiLi['user_bo_fy_balance'];
                }else{
                    $fy['fy_user_id'] = $companyUser['user_id'];
                    $fy['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fy['hf'] = 1;
                    $fy['freeze_name'] = $provinceDaiLi['user_real_name'];
                }
            }
        }elseif ($type == 2){
            // 市代
            $cityDaiLi = Db::table('up_u_user')
                ->where(['user_bo_district_role' => ['LIKE', '%,3,%'], 'user_agency_shi' => $district])
                ->field('user_id, user_agency_shi_status, user_bo_fy_balance, user_real_name')
                ->find();
            if($cityDaiLi){
                $bfc_id = 30;
                $fy['should_user_id'] = $cityDaiLi['user_id'];
                if($cityDaiLi['user_agency_shi_status'] == 1){
                    $fy['fy_user_id'] = $cityDaiLi['user_id'];
                    $fy['bo_balance'] = $cityDaiLi['user_bo_fy_balance'];
                }else{
                    $fy['fy_user_id'] = $companyUser['user_id'];
                    $fy['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fy['hf'] = 1;
                    $fy['freeze_name'] = $cityDaiLi['user_real_name'];
                }
            }
        }else{
            // 县代
            $districtDaiLi = Db::table('up_u_user')
                ->where(['user_bo_district_role' => ['LIKE', '%,2,%'], 'user_agency_qu' => $district])
                ->field('user_id, user_agency_qu_status, user_bo_fy_balance, user_real_name')
                ->find();
            if($districtDaiLi){
                $bfc_id = 29;
                $fy['should_user_id'] = $districtDaiLi['user_id'];
                if($districtDaiLi['user_agency_qu_status'] == 1){
                    $fy['fy_user_id'] = $districtDaiLi['user_id'];
                    $fy['bo_balance'] = $districtDaiLi['user_bo_fy_balance'];
                }else{
                    $fy['fy_user_id'] = $companyUser['user_id'];
                    $fy['bo_balance'] = $companyUser['user_bo_fy_balance'];
                    $fy['hf'] = 1;
                    $fy['freeze_name'] = $districtDaiLi['user_real_name'];
                }
            }
        }
        if($bfc_id != 0){
            $fy['ratio'] = Db::table('up_bo_fy_config')->where('bfc_id', $bfc_id)->value('bfc_content');
        }
        return $fy;
    }

    /*
     * 获取冻结期间用户获取的积分
     * @param $should_user   应该给谁的积分
     * @param $from          积分来源  1 团队长  2 县代  3 市代   4 省代
     * @param $company_user  公司平台账号ID
     * @param $time          时间
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFreezeFy($should_user, $from, $company_user, $time){
        $data = Db::table('up_bo_fy')
            ->where([
                'binte_user_id'        => $company_user,
                'binte_should_user_id' => $should_user,
                'binte_time'           => ['>', $time],
                'binte_from'           => $from,
                'binte_hf'             => 1,
                'binte_type'           => 1
            ])
            ->field('binte_id, binte_price')
            ->select();
        return $data;
    }

    /**
     * 插入脖脸皮分佣表
     * @param $user_id            实际获取佣金用户ID
     * @param $other_user_id      佣金产生着ID
     * @param $should_user_id     应该获取佣金用户ID
     * @param $freeze_user_id     因为谁被冻结了，导致我的分佣也被冻结
     * @param $type               佣金类型     1 佣金获取   2 佣金支出
     * @param $desc               描述
     * @param $cate               1 分佣   2 提现到银行卡    3 提现到积分  4 提现拒绝退回
     * @param $balance            佣金数量
     * @param $user_balance       用户现有佣金
     * @param $order_id           订单ID
     * @param $hf                 是否需要恢复      1 未恢复/需要恢复   2 已恢复/不需要恢复
     * @param $tc_from            提成来源  1 团队长提成   2 县代提成  3 市代提成  4 省代提成
     * @param $freeze_name        提成来源  是谁冻结了，导致分佣进了公司账户
     * @return int|string
     */
    public function insertBoFy($user_id = 0, $other_user_id = 0, $should_user_id = 0,
                               $freeze_user_id = 0, $type = 1, $desc = '', $cate = 1, $balance = 0,
                               $user_balance = 0, $order_id = 0, $hf = 2, $tc_from = 0, $freeze_name = ''){
        $order_number = 'BF_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $insert = [
            'binte_user_id'        => $user_id,
            'binte_other_user_id'  => $other_user_id,
            'binte_number'         => $order_number,
            'binte_type'           => $type,
            'binte_desc'           => $desc,
            'binte_price'          => $balance,
            'binte_front'          => $user_balance,
            'binte_after'          => $after,
            'binte_order_id'       => $order_id,
            'binte_time'           => date('Y-m-d H:i:s'),
            'binte_cate'           => $cate,
            'binte_should_user_id' => $should_user_id,
            'binte_freeze_user_id' => $freeze_user_id,
            'binte_from'           => $tc_from,
            'binte_hf'             => $hf,
            'binte_admin_id'       => session('username'),
            'binte_freeze_name'    => $freeze_name
        ];
        $inte_id = Db::table('up_bo_fy')->insertGetId($insert);
        return $inte_id;
    }

    /**
     * 插入脖脸皮积分表
     * @param $user_id            用户ID
     * @param $type               积分类型     1 积分获取   2 积分支出
     * @param $desc               积分描述
     * @param $balance            积分数量
     * @param $user_balance       用户现有积分
     * @param $order_id           订单ID
     */
    public function insertBoInte($user_id = 0, $type = 1, $desc = '', $balance = 0, $user_balance = 0, $order_id = 0){
        $order_number = 'BI_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $inte_id = Db::table('up_bo_integral')
            ->insertGetId([
                'binte_user_id'        => $user_id,
                'binte_number'         => $order_number,
                'binte_type'           => $type,
                'binte_desc'           => $desc,
                'binte_price'          => $balance,
                'binte_front'          => $user_balance,
                'binte_after'          => $after,
                'binte_order_id'       => $order_id,
                'binte_time'           => date('Y-m-d H:i:s'),
                'binte_admin_id'       => session('username')
            ]);
        return $inte_id;
    }

    /**
     * 特惠商品积分明细
     * @param $user_id       用户ID
     * @param $type          1 充值   2 支出
     * @param $desc          描述
     * @param $balance       积分
     * @param $user_balance  用户充值钱可用积分
     * @param $order_id      订单ID
     * @return int|string
     */
    public function insertThInte($user_id = 0, $type = 1, $desc = '', $balance = 0, $user_balance = 0, $order_id = 0){
        $num = 'THJF_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $inte = [
            'inte_user_id' => $user_id,
            'inte_num' => $num,
            'inte_type' => $type,
            'inte_des' => $desc,
            'inte_number' => $balance,
            'inte_front' => $user_balance,
            'inte_after' => $after,
            'inte_order_num' => $order_id,
            'inte_time' => date('Y-m-d H:i:s'),
            'inte_admin' => session('username')
        ];
        $inte_id = Db::table('up_integral')->insertGetId($inte);
        return $inte_id;
    }

    /**
     * 家大业大积分明细
     * @param $user_id       用户ID
     * @param $type          1 充值   2 支出
     * @param $desc          描述
     * @param $balance       积分
     * @param $user_balance  用户充值前可用积分
     * @param $order_id      订单ID
     * @return int|string
     */
    public function insertBigInte($user_id = 0, $type = 1, $desc = '', $balance = 0, $user_balance = 0, $order_id = 0){
        $num = 'BIG_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        if($type == 1){
            $after = $user_balance + $balance;
        }else{
            $after = $user_balance - $balance;
        }
        $inte = [
            'binte_user_id' => $user_id,
            'binte_number' => $num,
            'binte_type' => $type,
            'binte_desc' => $desc,
            'binte_price' => $balance,
            'binte_front' => $user_balance,
            'binte_after' => $after,
            'binte_order_id' => $order_id,
            'binte_time' => date('Y-m-d H:i:s'),
            'binte_admin_id' => session('username')
        ];
        $inte_id = Db::table('up_big_integral')->insertGetId($inte);
        return $inte_id;
    }

    /**
     * 用户启用/冻结操作记录
     * @param $user_id       用户ID
     * @param $type          1 登录   2 团队长   3 省代   4 市代  5 县代
     * @param $status        1 启用   2 冻结
     * @param $remark        备注
     * @return int|string
     */
    public function statusChange($user_id, $type, $status, $remark){
        $id = Db::table('up_use_freeze')
            ->insertGetId([
                'user_id' => $user_id,
                'type'    => $type,
                'status'  => $status,
                'remark'  => $remark,
                'admin'   => session('username'),
                'time'    => date('Y-m-d H:i:s')
            ]);
        return $id;
    }
}